import 'package:intl/intl.dart';
import 'db_helper.dart';

/// 拓展序列化方法 避免影响原始数据库文件
extension Serilizer on DBHelper {

  reStr(String oldStr){
    String newStr = oldStr.replaceAll("'", "''");
    return newStr;
  }
  /// 判断单词是否存在
  Future<Map> hasWords(String name) async {
    await initDB();
    String query = "SELECT * FROM $wordsTB WHERE name = '${reStr(name)}'";
    List<Map<String, dynamic>> res = await DBHelper.db!.rawQuery(query);
    if (res.isNotEmpty) {
      return {
        "id": res[0]['id'],
        "name": res[0]['name'],
        "trans": res[0]['trans'],
        "ukphone": res[0]['ukphone'],
        "ukspeech": res[0]['ukspeech'],
        "usphone": res[0]['usphone'],
        "usspeech": res[0]['usspeech'],
        "syno": res[0]['syno'],
        "relWord": res[0]['relWord'],
        "sentence": res[0]['sentence'],
        "phrase": res[0]['phrase'],
        "exam": res[0]['exam'],
        "belong": res[0]['belong'],
        "checkTimes": res[0]['checkTimes'],
        "errorTimes": res[0]['errorTimes'],
        "helpText": res[0]['helpText'],
        "soundText": res[0]['soundText'],
      };
    } else {
      return {};
    }
  }

  /// 获取当前记录的单词数据
  Future<Map> getCurrentWord(int bookId,int index) async {
    await initDB();
    String query = "SELECT * FROM $wordsTB WHERE belong LIKE '%${','+ bookId.toString() + ','}%' Limit 1 Offset $index";
    List<Map<String, dynamic>> res = await DBHelper.db!.rawQuery(query);
    if (res.isNotEmpty) {
      return {
        "id": res[0]['id'],
        "name": res[0]['name'],
        "trans": res[0]['trans'],
        "ukphone": res[0]['ukphone'],
        "ukspeech": res[0]['ukspeech'],
        "usphone": res[0]['usphone'],
        "usspeech": res[0]['usspeech'],
        "syno": res[0]['syno'],
        "relWord": res[0]['relWord'],
        "sentence": res[0]['sentence'],
        "phrase": res[0]['phrase'],
        "exam": res[0]['exam'],
        "belong": res[0]['belong'],
        "checkTimes": res[0]['checkTimes'],
        "errorTimes": res[0]['errorTimes'],
        "helpText": res[0]['helpText'],
        "soundText": res[0]['soundText'],
      };
    } else {
      return {};
    }
  }


}